<template>
    <div>

        <div style="text-align: center; width: 100%; height: 130px; background: white;">
            <div style="display: flex;">
                <van-icon name="arrow-left" @click="router.push('/taber/home')" style="font-size: 20px; margin-top:15px" />
                <input type="text" id="input_id" v-model="searchInput" placeholder="请输入你想住的位置"
                    style="z-index:999;width: 315px; border-radius: 5px; border: none;height: 36px; position: absolute; top: 6px; left:22px; background: rgb(242,242,242);" />
                <button
                    style="border: none; width: 70px; height: 36px; border-radius: 4px; background: rgb(245,124,0); color: white; position: absolute; top: 7px; z-index: 999; right: 10px;"
                    @click="search">
                    搜索
                </button>
            </div>
            <div style="width: 100%; position: absolute; top: 50px;">
                <van-dropdown-menu>
                    <van-dropdown-item key="sorter" title="位置">
                        <div style="padding: 12px;">
                            排序内容<br />
                            排序内容<br />
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item key="bizop" title="整租·户型">
                        <div style="padding: 12px;">
                            商机筛选内容<br />
                            商机筛选内容<br />
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item key="zu" title="租金">
                        <div style="padding: 12px;">
                            更多筛选内容<br />
                            更多筛选内容<br />
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item key="more" title="更多">
                        <div style="padding: 12px;">
                            更多筛选内容<br />
                            更多筛选内容<br />
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item key="pai" title="排序">
                        <div style="padding: 12px;">
                            更多筛选内容<br />
                            更多筛选内容<br />
                        </div>
                    </van-dropdown-item>
                </van-dropdown-menu>
            </div>
            <div v-if="show">
                <div class="tqd">
                    <div>
                        <h3>到公司要多久？</h3>
                        <p style="font-size: 19px">按出行路线查找合适房子</p>
                    </div>
                    <button @click="router.push('/commuter')">设置通勤地</button>
                </div>
            </div>
            <div v-else>
                <div class="tqd1">
                    <div class="tqd-box">
                        <div @click="setMode('driving')">
                            <img src="/public/imgage_gy/公交车.png" style="width: 30px; height: 30px;" />
                            <p>驾车</p>
                        </div>
                        <div @click="setMode('walking')">
                            <img src="/public//imgage_gy//步行.png" style="width: 30px; height: 30px;" />
                            <p>骑行</p>
                        </div>
                    </div>
                    <div class="tqd-box1">
                        <h3>预计{{ yjtime }}分钟</h3>
                        <p @click="router.push('/commuter')">
                            {{ searchInput }}
                            <van-icon name="arrow" />
                        </p>
                    </div>
                    <img src="/public/imgage_gy/垃圾桶.png" style="width: 26px; height: 26px; margin-top:60px;"
                        @click="toggleShow" />
                </div>
            </div>

            <!-- 
            <div v-if="loading" class="skeleton">
                <div class="skeleton-map"></div>
            </div> -->

        </div>
        <div class="animate__animated animate__fadeInDownBig">

            <div id="container" class="container" style="height: 785px; position: relative;top:-33px"></div>
        </div>


    </div>
</template>

<script lang="ts" setup>

import { defineComponent, ref, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import AMapLoader, { load } from '@amap/amap-jsapi-loader';


const route = useRoute()
const searchInput = ref('');
const show = ref(true);
const router = useRouter();
const yjtime = ref('')
let map: any = null;
let driving: any = null; //驾车路线规划对象
let walking: any = null;  //步行路线规划对象
let userPosition: any = null; //用户当前位置
const commuteData = ref([])
const loading = ref(true) //用来判断地图是否正在加载
const drivingMode = ref('driving'); //用来设置当前的出行模式，默认为driving

// 获取用户当前位置
const getCurrentPosition = () => {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const { latitude, longitude } = position.coords;
                    resolve([longitude, latitude])
                },
                (error) => reject(error),
                { enableHighAccuracy: true }
            )
        } else {
            reject(new Error('Geolocation is not supported by this browser'))
        }
    })
}

// 设置出行模式，并在模式切换后重新计算路线
const setMode = (mode: string) => {
    if (drivingMode.value !== mode) {
        drivingMode.value = mode;
        search()
    }
}

// 搜索功能：根据输入的地址进行路线规划
const search = () => {
    if (!searchInput.value.trim()) {
        alert('请输入有效的地址');
        return;
    }
    show.value = false;
    // 根据模式选择路线规划
    const routePlugin = drivingMode.value === 'driving' ? AMap.Driving : AMap.Walking;

    // 使用高德地理编码将地址转换为经纬度
    AMapLoader.load({
        key: 'a72455eb53629fab7fd81bb7812ae821', // 替换为你自己的高德API key
        version: '2.0',
        plugins: ['AMap.Geocoder'],
    }).then((AMap) => {
        const geocoder = new AMap.Geocoder();
        geocoder.getLocation(searchInput.value, (status, result) => {
            if (status === 'complete' && result.geocodes && result.geocodes.length > 0) {
                const targetPosition = result.geocodes[0].location
                // console.log(targetPosition, '1234');

                if (driving || walking) {
                    const routePlanner = new routePlugin({
                        map: map
                    })
                    routePlanner.search(userPosition, targetPosition, (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            const route = result.routes[0];
                            const routePath = route.steps.reduce((acc, step) => acc.concat(step.path), []);
                            // 在地图上绘制路线
                            const polyline = new AMap.Polyline({
                                path: routePath,
                                strokeColor: '#00FF00',
                                strokeWeight: 6,
                                strokeOpacity: 1,
                            });
                            map.add(polyline);

                            // 更新界面显示距离和预计时间
                            const distance = Math.floor(route.distance / 1000); // 单位：公里
                            const time = Math.ceil(route.time / 60); // 单位：分钟
                            yjtime.value = time
                            //  searchInput.value=''
                            alert(`距离：${distance}km, 预计时间：${time}分钟`);
                            // 存储当前的通勤地
                            const currentCommute = {
                                start: userPosition,
                                end: targetPosition,
                                distance: distance,
                                time: time,
                            };
                            commuteData.value.push(currentCommute);
                            localStorage.setItem('commuteData', JSON.stringify(commuteData.value));

                            map.setFitView(polyline);

                        } else {
                            console.error('路线规划失败', result);
                        }
                    });
                }
            } else {
                alert('无法找到该地址');
            }
        });
    }).catch((error) => {
        console.error('高德地图加载失败', error);
    });
};
// 初始化地图和路线规划功能
onMounted(async () => {
    searchInput.value = route.query.tqm || ''; //获取query中的tqm参数 
    if (searchInput.value.trim()) {
        search()
    }
    userPosition = await getCurrentPosition();
    window._AMapSecurityConfig = {
        securityJsCode: '748ff078c60465cdda98b8248e226b20', // 替换为你的高德安全码
    };

    AMapLoader.load({
        key: 'a72455eb53629fab7fd81bb7812ae821', // 替换为你自己的高德API key
        version: '2.0',
        plugins: ['AMap.Driving', 'AMap.Walking', 'AMap.Geocoder', 'AMap.Autocomplete'],
    }).then((AMap) => {
        map = new AMap.Map('container', {
            zoom: 15,
            center: userPosition,
        });

        // 根据当前的出行模式。进行初始化相应的路线规划
        if (drivingMode.value === 'driving') {
            driving = new AMap.Driving({
                map: map,
            })
        } else {
            walking = new AMap.Walking({
                map: map,
            })
        }

        // 标记当前位置
        const marker = new AMap.Marker({
            position: userPosition,
            map: map,
            title: '当前位置',
        });

        // 地图加载完成，关闭骨架屏
        // loading.value = false
    }).catch((e) => {
        console.error('高德地图加载失败', e);
        // loading.value = false
    });
});


const toggleShow = () => {
    show.value = !show.value;
    searchInput.value = ''
    yjtime.value = ''

    if (driving) {
        driving.clear()
    }
    if (walking) {
        walking.clear()
    }
    // 并将搜索的路线删除
    if (map && (driving || walking)) {
        map.clearMap();//清除地图上的路线
        // 然后重置地图的位置，回到用户当前的位置上
        map.setCenter(userPosition)
        map.setZoom(15);  //默认缩放级别
    }
    if (route.query.tqm) {
        router.replace({ query: { ...route.query, tqm: undefined } }).catch(() => { })
    }

};

onUnmounted(() => {
    map?.destroy();
});


</script>



<style scoped>
/* This only changes this particular animation duration */
.animate__animated.animate__fadeInDownBig {
    --animate-duration: 2s;
}

/* This changes all the animations globally */
:root {
    --animate-duration: 800ms;
    --animate-delay: 0.9s;
}

.tqd {
    width: 380px;
    height: 100px;
    background-color: white;
    position: absolute;
    bottom: 50px;
    left: 25px;
    z-index: 999;
    border-radius: 10px;
    display: flex;
    justify-content: space-around;
}

.tqd1 {
    width: 380px;
    height: 100px;
    background-color: white;
    position: absolute;
    bottom: 76px;
    left: 25px;
    z-index: 999;
    border-radius: 10px;
    display: flex;
    justify-content: space-around;
}

.tqd div {
    text-align: left;
}

.tqd button {
    width: 100px;
    height: 50px;
    border: none;
    background-color: rgb(245, 124, 0);
    color: white;
    border-radius: 5px;
    margin-top: 22px;
    font-size: 15px;
}

.tqd1 .tqd-box {
    width: 110px;
    display: flex;
    justify-content: space-between;
    /* background-color: aqua; */
    margin-left: 0px;
    margin-top: 20px;
}

.tqd1 .tqd-box1 {}

.skeleton {
    width: 100%;
    height: 100vh;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.skeleton-map {
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    animation: shimmer 1s infinite linear;
}

@keyframes shimmer {
    0% {
        background-position: -200px 0;
    }

    100% {
        background-position: 200px 0;
    }
}
</style>